package pers.mobian.aop;

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.Pointcut;
import org.springframework.aop.PointcutAdvisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.StaticMethodMatcherPointcut;

import java.lang.reflect.Method;

/**
 * @Date 2021/10/8 21:04
 * @Created mobian
 * @Description
 */
public class ProxyFactoryTest2 {
	public static void main(String[] args) {

		UserService service = new UserServiceImpl();
		ProxyFactory factory = new ProxyFactory();
		factory.setTarget(service);

		// Advice + Pointcut = Advisor
		factory.addAdvice(new MoBeforeAdvice());
		// 添加一个粒度更细的代理逻辑
		factory.addAdvisor(new PointcutAdvisor() {
			@Override
			public Pointcut getPointcut() {
				return new StaticMethodMatcherPointcut() {
					@Override
					public boolean matches(Method method, Class<?> targetClass) {
						// 如果方法名字是test,就执行对应的代理逻辑
						return method.getName().equals("test");
					}
				};
			}
			// 对test方法使用的代理类
			@Override
			public Advice getAdvice() {
				return new MoAfterAdvice();
			}

			@Override
			public boolean isPerInstance() {
				return false;
			}
		});

		UserService proxy = (UserService) factory.getProxy();
		proxy.show();
		System.out.println("----");
		proxy.test();
	}
}
